#!/bin/bash
WORKDIR=_ipkg_work/
TEMPDIR=_ipkg_temp/
COMICDIR=/usr/share/comic_reader/comic
COMIC_PACKER=./comic_packer
CONTROL=control
BINARY="debian-binary"
DATA="data.tar.gz"

if (( $# == 0));then
	echo "Usage: $0 <directory>"
	exit
fi

BOOKDIR=`basename $1`

if ! [ -d $BOOKDIR ];then
	echo "argument should be directory"
	exit
fi


if ! [ -e $COMIC_PACKER ]; then
	echo "You should compile comic_packer first"
	echo " > ./configure"
	echo " > make"
	echo "May helps"
	exit
fi

if [ -e $WORKDIR ];then 
	rm -rf $WORKDIR
fi
if [ -e $TEMPDIR ];then
	rm -rf ${TEMPDIR}
fi	

echo "Please enter your description about this package: (in one line)"
echo -n ">"
read DESCRIPTION
echo "What name you want to be known? "
echo -n ">"
read WHOAMI
echo "The comic_reader data directory? [$COMICDIR]" 
echo "(If right please enter directly, or type it)"
echo -n ">"
read COMICDIRTMP

if [ $COMICDIRTMP ];then
  COMICDIR=$COMICDIRTMP
fi

mkdir -p ${WORKDIR}/${COMICDIR}
mkdir -p ${TEMPDIR}
${COMIC_PACKER}  -o  ${WORKDIR}/${COMICDIR}/$BOOKDIR.eet $BOOKDIR
pushd ${WORKDIR}
  	tar -czf ../${TEMPDIR}/${DATA} .
	rm -rf usr
	echo "Package: comic-book-$BOOKDIR"   >  ${CONTROL} 
	echo "Version: 0.1"		>> ${CONTROL}
	echo "Description: $DESCRIPTION">> ${CONTROL}
	echo "Section: base"		>> ${CONTROL}
	echo "Priority: optional"	>> ${CONTROL}
	echo "Maintainer: $WHOAMI"	>> ${CONTROL}
	echo "Architecture: all"	>> ${CONTROL}
	echo "OE: comic_reader"		>> ${CONTROL}
	echo "Homepage: http://code.google.com/p/comic-reader" 	     >>  ${CONTROL}
	echo "Tags: group::games"	>> ${CONTROL}
	echo "Depends: comic-reader"	>> ${CONTROL}
	echo "Source: http://comic-reader.googlecode.com/svn/trunk/" >>  ${CONTROL}
	tar -czf ../${TEMPDIR}/${CONTROL}.tar.gz .
	rm -rf usr ${CONTROL}
popd

pushd ${TEMPDIR}
  	echo "2.0" > "${BINARY}"
	ar -crf comic-book-${BOOKDIR}_0.1_all.ipk ${BINARY} ${DATA} ${CONTROL}.*
	mv *.ipk ..
popd

rm -rf  ${WORKDIR}
rm -rf  ${TEMPDIR}
